package com.g03.hj;

import java.util.HashSet;
import java.util.Set;

public class Code {
    public int majorityElement(int[] nums) {
        // https://leetcode.cn/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/
        // 数组中出现次数超过一半的元素
        int res = nums[0], t = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == res) {
                t++;
            } else if (t != 0) {
                t--;
            } else {
                res = nums[i];
                t = 1;
            }
        }
        return res;
    }

    public int singleNumber(int[] nums) {
        // https://leetcode.cn/problems/single-number/
        // 只出现一次的数字
        int res = 0;
        for (int i : nums) {
            res = res ^ i;
        }
        return res;
    }

    public int findRepeatNumber(int[] nums) {
        // https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
        // 数组中重复的数字
        Set<Integer> s = new HashSet<>();
        for (int i : nums) {
            if (s.contains(i)) {
                return i;
            }
            s.add(i);
        }
        return -1;
    }

    public void sortColors(int[] nums) {
        // https://leetcode.cn/problems/sort-colors/
        // 颜色分类
        int left = 0, cur = 0, right = nums.length - 1;
        int temp;
        while(cur <= right) {
            switch(nums[cur]) {
                case 0:
                    temp = nums[cur];
                    nums[cur] = nums[left];
                    nums[left] = temp;
                    cur++;
                    left++;
                    break;
                case 1:
                    cur++;
                    break;
                case 2:
                    temp = nums[right];
                    nums[right] = nums[cur];
                    nums[cur] = temp;
                    right--;
                    break;
            }
        }
    }
}
